package common

import (
	"errors"
	"fmt"
	"github.com/casbin/casbin/v2"
	gormadapter "github.com/casbin/gorm-adapter/v3"
	"mycms/global"
	"mycms/model/system"
	systemReq "mycms/model/system/request"
	"sync"
)

var (
	syncedEnforcer *casbin.SyncedEnforcer
	once           sync.Once
)
type CasbinService struct{}

var CasbinServiceApp = new(CasbinService)


func (casbinService *CasbinService)Casbin() *casbin.SyncedEnforcer {
	once.Do(func() {
		a, err := gormadapter.NewAdapterByDB(global.DB)
		if err != nil {
			fmt.Printf("数据库错误：", err.Error())
		}
		syncedEnforcer, err = casbin.NewSyncedEnforcer(global.CONFIG.Casbin.ModelPath, a)
		if err != nil {
			fmt.Printf("创建失败：",err.Error())
		}
	})

	// 加载策略
	_ = syncedEnforcer.LoadPolicy()
	return syncedEnforcer
}

func (casbinService *CasbinService) UpdateCasbin(authorityId string, casbinInfos []systemReq.CasbinInfo) error {
	casbinService.ClearCasbin(0, authorityId)

	rules := [][]string{}
	for _, v := range casbinInfos {
		cm := system.CasbinModel{
			Ptype:       "p",
			AuthorityId: authorityId,
			Path:        v.Path,
			Method:      v.Method,
		}
		rules = append(rules, []string{cm.AuthorityId, cm.Path, cm.Method})
	}
	e := casbinService.Casbin()
	success, _ := e.AddPolicies(rules)
	if !success {
		return errors.New("存在相同api,添加失败,请联系管理员")
	}
	return nil
}

//@function: ClearCasbin
//@description: 清除匹配的权限
//@param: v int, p ...string
//@return: bool

func (casbinService *CasbinService) ClearCasbin(v int, p ...string) bool {
	e := casbinService.Casbin()
	success, _ := e.RemoveFilteredPolicy(v, p...)
	return success
}
